package com.example.connection.ui.connection;

import android.bluetooth.BluetoothDevice;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.connection.MainActivity;
import com.example.connection.MyViewHolder;
import com.example.connection.R;
import com.example.connection.databinding.ChatFragmentBinding;
import com.example.connection.databinding.FragmentConnBinding;
import com.example.connection.ui.chat.ChatViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ConnFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ConnFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private FragmentConnBinding binding;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    RecyclerView mRecyclerView;
    MyAdapter mMyAdapter;
    List<BluetoothDevice> MyDeviceList = new ArrayList<BluetoothDevice>();
    private ConnViewModel mViewModel;
    MainActivity activity;
    RadioGroup radioGroup;
    public ConnFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ConnFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ConnFragment newInstance(String param1, String param2) {
        ConnFragment fragment = new ConnFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity) getActivity();
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mViewModel = new ViewModelProvider(this).get(ConnViewModel.class);
        binding = FragmentConnBinding.inflate(inflater, container, false);
        mRecyclerView = binding.DeviceRecyclerView;
        radioGroup=binding.myRadioGroup;
        mRecyclerView.setVisibility(View.VISIBLE);
        binding.setNotify.setVisibility(View.VISIBLE);
        binding.startAdvertising.setVisibility(View.INVISIBLE);
        activity.isMaster = true;
        binding.setNotify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.setF1Notify(true);
            }
        });
        View root = binding.getRoot();
//        if (activity==null){
//            Log.i("mytag","activity为null");
//        }else if (activity.BTDeviceListData==null){
//            Log.i("mytag","activity.BTDeviceListData==null");
//        }
        //通过observe更新mMyAdapter
        activity.BTDeviceListData.observe(getViewLifecycleOwner(), new Observer<List>() {
            @Override
            //值赋给list
            public void onChanged(List list) {
                //将list（BTDeviceListData）赋给MyDeviceList
                MyDeviceList = list;
                //更新列表adapter
                mMyAdapter.notifyDataSetChanged();
            }
        });
        mMyAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mMyAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        mRecyclerView.setLayoutManager(layoutManager);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Log.i("mytag","i是："+i);
                Log.i("mytag","master是："+R.id.master+"slave是："+R.id.slave);

                switch (i){
                    case R.id.master:
                        mRecyclerView.setVisibility(View.VISIBLE);
                        binding.setNotify.setVisibility(View.VISIBLE);
                        binding.startAdvertising.setVisibility(View.INVISIBLE);
                        activity.isMaster = true;
                        break;
                    case R.id.slave:
                        mRecyclerView.setVisibility(View.INVISIBLE);
                        binding.setNotify.setVisibility(View.INVISIBLE);
                        binding.startAdvertising.setVisibility(View.VISIBLE);
                        activity.isMaster = false;
                        break;

                    default:
                        break;
                }
            }
        });
        binding.startAdvertising.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.startAdvertising();
            }
        });
        return root;

    }

    public ConnViewModel getViewModel() {
        return mViewModel;
    }

    //设置RecyclerView adapter
    class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(getActivity(), R.layout.content_main_item, null);
            MyViewHolder myViewHolder = new MyViewHolder(view);
            return myViewHolder;

        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            //设置列表数据
            holder.name.setText(MyDeviceList.get(position).getName());
            holder.mac.setText(MyDeviceList.get(position).getAddress());
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //调用连接方法
                   activity.connectDeviceWithIndex(holder.getAdapterPosition());
                   Toast.makeText(activity, "点击了第" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
                   Log.i("mytag",""+holder.getAdapterPosition());
                }
            });
//            holder.name.setText("name");
//            holder.mac.setText("1.1.1.1.1");
        }
        @Override
        public int getItemCount() {
            Log.i("mytag", "size:" + MyDeviceList.size());
            return MyDeviceList.size();

        }
    }
}